package com.sunny.fetch.dao.data;

import com.alibaba.fastjson.JSON;
import com.sunny.fetch.dao.exception.DecodeException;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Author: sublun
 * @Date: 2021/3/31 15:21
 */
public class DataObject extends LinkedHashMap {
    private List<DataObject> list;

    public DataObject() {
        list = new LinkedList<>();
    }
    /**
     * Create an instance from a string of JSON
     *
     * @param json the string of JSON
     */
    public DataObject(String json) throws DecodeException {
        if (json == null) {
            throw new NullPointerException();
        }
        fromJson(json);
        if (this.keySet().size() == 0 && list == null) {
            throw new DecodeException("Invalid JSON object: " + json);
        }
    }
    private void fromJson(String json) {
        try {
            Map map = JSON.parseObject(json, Map.class);
            this.putAll(map);
        } catch (Exception e) {

            try {
                list = JSON.parseArray(json, DataObject.class);
            } catch (Exception e1){
                e1.printStackTrace();
            }
        }

    }


}
